<?php
/*
 * @分销商城
 * @功能说明：订单主业务
 * @更新说明：暂无更新
 * @文件名 OrderController.class.php
 * @编码 UTF-8
 * @创建时间 2016-1-23 下午1:48:30
 * @创建人 XING
 */
namespace dg\Controller;

use Think\Controller;

class OrderController extends ApibaseController
{
    function __construct() {
        parent::__construct();
        $this->_OrderCollectModel = D('OrderCollect');
    }

    /*
     * 分销商城_订单主页NEW
     * @date: 2015-12-25 下午4:49:04
     * @editor: XING
     */
    public function index() {
        /*参数初始化*/
        $page = I('get.page') ?: 1;
        $perpage = 10;
        $url = '';
        $list = M('OrderEntity')->where(array('otype' => '0'));
        $url = $output = $outtype = array();
        if (I('get.cust_realname')) {
            $list = $list->where('cust_realname LIKE "%' . I('get.cust_realname') . '%"');
            $url['cust_realname'] = I('get.cust_realname');
        }
        if (I('get.cust_mobile')) {
            $list = $list->where(array('receive_mobile' => I('get.cust_mobile')));
            $url['cust_mobile'] = I('get.cust_mobile');
        }
        if (I('get.cust_id')) {
            $list = $list->where(array('cust_id' => I('get.cust_id')));
            $url['cust_id'] = I('get.cust_id');
        }
        if (I('get.order_id')) {
            $list = $list->where(array('order_id' => I('get.order_id')));
            $url['order_id'] = I('get.order_id');
        }
        if (I('get.cust_id')) {
            $list = $list->where(array('cust_id' => I('get.cust_id')));
            $url['cust_id'] = I('get.cust_id');
        }

        if ((I('get.st') > -2 && isset($_GET['st'])) && !in_array(I('get.st'), array('all', 'refund'))) {
            $list = $list->where(array('order_status' => I('get.st')));
            $url['st'] = I('get.st');
        } elseif (I('get.st') == 'refund') {
            $list = $list->where('order_status IN(5,6,7,8,9)');
            $url['st'] = I('get.st');
        }
        $custObject = clone $list;
        $getData = $list->order(array('add_at' => 'desc'))->page($page, $perpage)->select();
        $this->assign('page', setPage($custObject->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->display('order/index');
    }

    /*
     * 分销商城_订单取消NEW
     * @date: 2015-12-28 下午12:04:25
     * @editor: XING
     */
    public function cancle() {
        if (I('get.oid')) {
            $checkStatus = M('OrderEntity')
                ->getFieldByOrderId(I('get.oid'), 'order_status');
            if (!in_array($checkStatus, array('0')))
                $this->showtips('非有效时段订单');
            $setCancle = M('OrderEntity')
                ->where(array('order_id' => I('get.oid')))->setField(array(
                    'order_status' => '-1'
                ));
            if ($setCancle) {
                $this->showtips('订单已取消');
            } else {
                $this->showtips('操作失败');
            }
        } else {
            $this->showtips('参数有误');
        }
    }

    /*
     * 分销商城_订单售后
     * @date: 2015-12-29 下午5:14:13
     * @editor: XING
     */
    public function refund() {
        if (I('post.dosubmit')) {
            if (in_array(I('post.status'), array('3', '5')) && I('post.id')) {
                $orderMain = M('OrderEntity');
                if (I('post.status') == '5') {
                    //todo 如果订单没有物流单号 直接把款退到用户账户上
                    $getExpress = M('OrderCollect')->where(array('order_id' => I('post.id')))->where("express_num != ''")->count();
                    if ($getExpress > 0) {
                        $orderMain->startTrans();
                        $orderEffect = $orderMain->lock(true)
                            ->where(array('order_id' => I('post.id')))->setField(array(
                                'refund_address' => trim(I('post.refund_address')),
                                'order_status'   => '6',
                                'refund_mark'    => I('post.remark') ?: '',
                                'refund_address' => I('post.refund_address')
                            ));
                        if ($orderEffect) {
                            $orderMain->commit();
                            //$this->showtips('同意退款，待买家寄回');
                            dataFormat('', 1, '同意退款，待买家寄回');
                        } else {
                            $orderMain->rollback();
                            dataFormat('', 0, '操作失败');
                            //$this->showtips('操作失败');
                        }
                    } else {
                        dataFormat('', 2);
                    }
                } else {
                    $orderEffect = $orderMain
                        ->where(array('order_id' => I('post.id')))->setField(array(
                            'order_status' => '7',
                            'refund_mark'  => I('post.remark')
                        ));
                    if ($orderEffect) {
                        dataFormat('', 1, '操作成功，已拒绝退款');
                        //$this->showtips('操作成功，已拒绝退款');
                    } else {
                        dataFormat('', 0, '操作失败');
                        //$this->showtips('操作失败');
                    }
                }
            } else {
                dataFormat('', 0, '参数有误，操作失败');
                //$this->showtips('参数有误，操作失败');
            }
        } elseif (I('get.oid')) {
            $custData = M('OrderEntity')
                ->where(array('order_id' => I('get.oid')))->find();
            $conf_val = M('ConfigSet')->where(array('config_column' => 'refundAddress'))->getField('config_val');
            $arr = explode('#', $conf_val);
            $result = array();
            foreach ($arr as $key => $vo) {
                $result[$key] = explode('|', $vo);
            }
            $conf_address = array();
            foreach ($result as $value) {
                $conf_address[] = '收货人:' . $value[0] . ',联系电话:' . $value[1] . ',退货地址:' . $value[2];
            }
            $this->assign('arr', $conf_address);
            $this->assign('sData', $custData);
            $this->display('order/refund');
        }
    }

    /*
     * 分销商城_订单备注
     * @date: 2016-06-03 15:38:00
     * @editor: WENCUN
     * */
    public function addRemark() {
        if (I('post.dosubmit') && I('post.oid') && I('post.remark')) {
            $data = array(
                'remark'    => I('post.remark'),
                'update_at' => time()
            );
            $setRemark = M('OrderEntity')->where(array('order_id' => I('post.oid')))->save($data);
            if ($setRemark) {
                $this->showtips('操作成功');
            } else {
                $this->showtips('操作失败');
            }
        } else {
            if (I('get.oid')) {
                $getRemark = M('OrderEntity')->field(array('remark'))->where(array('order_id' => I('get.oid')))->find();
                $this->assign('remark', $getRemark);
                $this->assign('flag', 1);
            }
            $this->display('/order/remark');
        }
    }

    /*
     * 分销商城_退货理由
     * @date: 2016-04-08 18:52:00
     * @editor: WENCUN
     * */
    public function refundly() {
        $custData = M('OrderEntity')
            ->where(array('order_id' => I('get.oid')))->find();
        $refunds = explode(',', getSysConfig('refundType'));
        $refundsImgs = explode(',', $custData['refund_imgs']);
        foreach ($refundsImgs as $key => $value) {
            $refundsImgs[$key] = transUrl($value);
        }
        $this->refundsImgs = $refundsImgs;
        $this->assign('refunds', $refunds);
        $this->assign('sData', $custData);
        $this->display('order/refundly');
    }

    /*
     * 分销商城_退货物流信息
     * @date: 2016-04-12 09:25:00
     * @editor: WENCUN
     * */
    public function refundwl() {
        $custData = M('OrderEntity')
            ->where(array('order_id' => I('get.oid')))->find();
        $this->assign('sData', $custData);
        $this->display('order/refundwl');
    }

    /*
     * 分销商城_订单发货
     * @date: 2015-12-29 下午5:14:13
     * @editor: XING
     */
    public function send() {
        if (I('post.dosubmit') && I('post.id')) {
            $orderMain = M('OrderCollect');
            $orderEffect = $orderMain->where(array('order_id' => I('post.id')))->setField(array(
                'express_at'   => time(),
                'express_name' => I('post.express_name'),
                'express_num'  => I('post.express')
            ));
            if ($orderEffect) {
                //更新订单状态
                M('OrderEntity')->where(array('order_id' => I('post.id')))->setField(array('order_status' => '2'));
                $this->showtips('发货成功');
            } else {
                $this->showtips('操作失败');
            }
        } elseif (I('get.oid')) {
            $oData = M('OrderEntity')
                ->where(array('order_id' => I('get.oid')))->find();
            if ($oData['order_status'] != '1') {
                $this->assign('wmsg', '无效订单号');
            }
            $this->express = explode(',', getSysConfig('expressComp'));
            $this->assign('sData', $oData);
            $this->display('order/send');
        }
    }

    /*
     * 分销商城_订单退款
     * @date: 2015-12-29 下午5:14:13
     * @editor: XING
     */
    public function refundmon() {
        if (I('post.dosubmit')) {
            if (in_array(I('post.status'), array('8', '9')) && I('post.id')) {
                $orderMain = M('OrderEntity');
                if (I('post.status') == '8') {
                    $upsArr = array(
                        'order_status' => '8',
                    );
                    I('post.remark') ? $upsArr['refund_mark'] = trim(I('post.remark')) : '';
                    $orderMain->startTrans();
                    if (I('post.order_status') && I('post.order_status') == '5') {
                        $orderEffect = $orderMain->lock(true)
                            ->where(array('order_id' => I('post.id'), 'order_status' => I('post.order_status')))->setField($upsArr);
                    } else {
                        $orderEffect = $orderMain->lock(true)
                            ->where(array('order_id' => I('post.id'), 'order_status' => '6'))->setField($upsArr);
                    }
                    if ($orderEffect) {
                        $checkProfit = M('GoodsProfit')
                            ->where(array('order_id' => I('post.id'), 'is_profit' => '1'))->count();
                        if ($checkProfit > 0) {
                            $uBottler = M('GoodsProfit');
                            $putReback = $uBottler->lock(true)
                                ->where(array('order_id' => I('post.id'), 'is_profit' => '1'))->setField(array(
                                    'is_profit' => '2',
                                    'update_at' => time()
                                ));
                            if ($putReback) {
                                $getChargeOrder = M('PayChannel')
                                    ->where(array('order_id' => I('post.id')))->find();
                                if ($getChargeOrder) {
                                    $getOrderDesc = M('OrderEntity')->field('pay_money')
                                        ->where(array('order_id' => I('post.id')))->find();
                                    $reQuest = (new \service\ping\Ping)->payRefund($getChargeOrder['charge_id'], I('post.id'), $getOrderDesc['pay_money']);
                                    $dataBack = json_decode($reQuest, 1);
                                    if ($dataBack['id']) {
                                        M('PayChannel')->where(array('order_id' => I('post.id')))->setField(array(
                                            'refund_id' => $dataBack['id']
                                        ));
                                        if ($getChargeOrder['pay_channel'] == 'alipay') {
                                            $url = str_replace('Open url for refund: ', '', $dataBack['failure_msg']);
                                            putlog('申请退款通过，提交支付页面 ', 'OrderController', 'refundmon');

                                            echo json_encode(array('msg' => 'success', 'url' => $url, 'type' => 'url'));
                                            exit;
                                        } elseif ($getChargeOrder['pay_channel'] == 'wx_pub') {
                                            putlog('申请退款通过，提交银行处理 ', 'OrderController', 'refundmon');
                                            //echo json_encode(array('msg'=>'操作成功','type'=>'other','code'=>'1'));
                                        }
                                        $uBottler->commit();
                                        $orderMain->commit();
                                        //$this->showtips('退款成功');
                                        //curl('http://192.168.0.132/jsssdk/refund',array('order_id'=>I('post.id')));
                                        curl('http://wap.hipaygo.cn/jsssdk/refund', array('order_id' => I('post.id')));
                                        dataFormat('', 1, '退款成功');
                                    } else {
                                        $orderMain->rollback();
                                        $uBottler->rollback();
                                        //$this->showtips('操作失败');
                                        dataFormat('', 0, '操作失败1');
                                        jsonRespons(0, '退款Api发起失败');
                                    }
                                } else {
                                    $orderMain->rollback();
                                    $uBottler->rollback();
                                    //$this->showtips('操作失败');
                                    dataFormat('', 0, '操作失败2');
                                }
                            } else {
                                $orderMain->rollback();
                                $uBottler->rollback();
                                //$this->showtips('操作失败');
                                dataFormat('', 0, '操作失败3');
                            }
                        } else {
                            //@todo  发起退款请求，成功后回调。
                            $uBottler = M('GoodsProfit');
                            $putReback = $uBottler->lock(true)
                                ->where(array('order_id' => I('post.id')))->where('is_profit IN(0,3)')->setField(array(
                                    'is_profit' => '-1',
                                    'update_at' => time()
                                ));
                            if ($putReback) {
                                $getChargeOrder = M('PayChannel')
                                    ->where(array('order_id' => I('post.id')))->find();
                                if ($getChargeOrder) {
                                    //@todo  发起退款请求，成功后回调。
                                    $getOrderDesc = M('OrderEntity')->field('pay_money')
                                        ->where(array('order_id' => I('post.id')))->find();
                                    $reQuest = (new \service\ping\Ping)->payRefund($getChargeOrder['charge_id'], I('post.id'), $getOrderDesc['pay_money']);
                                    $dataBack = json_decode($reQuest, 1);
                                    if ($dataBack['id']) {
                                        M('PayChannel')->where(array('order_id' => I('post.id')))->setField(array(
                                            'refund_id' => $dataBack['id']
                                        ));
                                        if ($getChargeOrder['pay_channel'] == 'alipay') {
                                            $url = str_replace('Open url for refund: ', '', $dataBack['failure_msg']);
                                            putlog('申请退款通过，提交支付页面 ', 'OrderController', 'refundmon');

                                            echo json_encode(array('msg' => 'success', 'url' => $url, 'type' => 'url'));
                                            exit;
                                        } elseif ($getChargeOrder['pay_channel'] == 'wx_pub') {
                                            putlog('申请退款通过，提交银行处理 ', 'OrderController', 'refundmon');
                                            echo json_encode(array('msg' => '操作成功', 'type' => 'other', 'code' => '1'));
                                        }
                                        $uBottler->commit();
                                        $orderMain->commit();
                                        //$this->showtips('退款成功');
                                        //curl('http://192.168.0.132/jsssdk/refund',array('order_id'=>I('post.id')));
                                        curl('http://wap.hipaygo.cn/jsssdk/refund', array('order_id' => I('post.id')));
                                        dataFormat('', 1, '退款成功');
                                    } else {
                                        $orderMain->rollback();
                                        $uBottler->rollback();
                                        //$this->showtips('操作失败');
                                        dataFormat('', 0, '操作失败');
                                        jsonRespons(0, '退款Api发起失败');
                                    }
                                } else {
                                    $orderMain->rollback();
                                    $uBottler->rollback();
                                    //$this->showtips('操作失败');
                                    dataFormat('', 0, '操作失败');
                                }
                            } else {
                                $orderMain->rollback();
                                $uBottler->rollback();
                                //$this->showtips('操作失败');
                                dataFormat('', 0, '操作失败');
                            }
                        }
                    } else {
                        $orderMain->rollback();
                        //$this->showtips('操作失败');
                        dataFormat('', 0, '操作失败4');
                    }
                } else {
                    $orderEffect = $orderMain
                        ->where(array('order_id' => I('post.id'), 'order_status' => '6'))->setField(array(
                            'order_status' => '7',
                        ));
                    if ($orderEffect) {
                        //$this->showtips('操作成功，已拒绝退款');
                        dataFormat('', 1, '操作成功，已拒绝退款');
                    } else {
                        //$this->showtips('操作失败');
                        dataFormat('', 0, '操作失败');
                    }
                }
            } else {
                //$this->showtips('参数有误，操作失败');
                dataFormat('', 0, '参数有误，操作失败');
            }
        } elseif (I('get.oid')) {
            $custData = M('OrderEntity')
                ->where(array('order_id' => I('get.order_id')))->find();
            $this->assign('sData', $custData);
            $this->display('order/refundmon');
        }
    }

    /*
     * 查看物流
     * @date: 2016-06-12 10:53:00
     * @editor: GaoChao
     */
    public function showExpress() {
        if (I('get.order_id')) {
            $express_info = $this->_OrderCollectModel->getOrderCollect(array('express_name', 'express_num', 'express_at'), array('order_id' => I('get.order_id')));
            $this->assign('express_info', $express_info);
        }
        $this->display('/order/express');
    }

    /*
     * 分销商城_客服备注
     * @date: 2016-06-03 15:38:00
     * @editor: GaoChao
     * */
    public function addServiceMark() {
        if (I('post.dosubmit') && I('post.oid') && I('post.remark')) {
            $data = array(
                'service_mark'    => I('post.remark'),
                'update_at' => time()
            );
            $setRemark = M('OrderEntity')->where(array('order_id' => I('post.oid')))->save($data);
            if ($setRemark) {
                $this->showtips('操作成功');
            } else {
                $this->showtips('操作失败');
            }
        } else {
            if (I('get.oid')) {
                $getRemark = M('OrderEntity')->field(array('service_mark'))->where(array('order_id' => I('get.oid')))->find();
                $getRemark ['remark'] = $getRemark ['service_mark'];
                $this->assign('remark', $getRemark);
                $this->assign('flag', 2);
            }
            $this->display('/order/remark');
        }
    }
}